package com.demo.多线程;

/**
 * @Program: java
 * @ClassName DeadLock
 * @Author: liutao
 * @Description: 死锁的产生
 * @Create: 2023-10-27 12:45
 * @Version 1.0
 **/

public class DeadLock {
    public static void main(String[] args) {
        MakeUp t1 = new MakeUp(0, "小明");
        MakeUp t2 = new MakeUp(1, "小红");

        new Thread(t1).start();
        new Thread(t2).start();

    }
}

class Phone {

}

class EarPhone {

}

class MakeUp implements Runnable {
    static Phone phone = new Phone();
    static EarPhone earPhone = new EarPhone();
    private final int choice;
    private final String name;

    MakeUp(int choice, String name) {
        this.choice = choice;
        this.name = name;
    }

    @Override
    public void run() {
        solveDeadlock();
    }

    /**
     * 死锁的产生
     **/
    private void deadLock() {
        if (this.choice == 0) {
            synchronized (phone) {
                System.out.println(this.name + "获得了手机的锁");
                synchronized (earPhone) {
                    System.out.println(this.name + "获得了耳机的锁");
                }
            }
        } else {
            synchronized (earPhone) {
                System.out.println(this.name + "获得了耳机的锁");
                synchronized (phone) {
                    System.out.println(this.name + "获得了手机的锁");
                }
            }
        }
    }

    /**
     * 解决死锁
     **/
    private void solveDeadlock() {
        if (this.choice == 0) {
            synchronized (phone) {
                System.out.println(this.name + "获得了手机的锁");
            }
            synchronized (earPhone) {
                System.out.println(this.name + "获得了耳机的锁");
            }
        } else {
            synchronized (earPhone) {
                System.out.println(this.name + "获得了耳机的锁");
            }
            synchronized (phone) {
                System.out.println(this.name + "获得了手机的锁");
            }
        }
    }


}
